package com.hspedu.springcloud.controller;

import com.hspedu.springcloud.entity.Member;
import com.hspedu.springcloud.entity.Result;
import com.hspedu.springcloud.service.MemberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * @author 韩顺平
 * @version 1.0
 */
@RestController
@Slf4j
public class MemberController {

    //装配MemberService
    @Resource
    private MemberService memberService;

    //添加方法/接口
    //这里请小伙伴回顾, 应该如何提交
    //老韩说明
    //1. 我们的前端如果是以json格式来发送添加信息Member， 那么我们需要使用@RequestBody
    //   , 才能将数据封装到对应的bean, 同时保证http的请求头的 content-type是对应
    //2. 如果前端是以表单形式提交了，则不需要使用@RequestBody, 才会进行对象参数封装, 同时保证
    //   http的请求头的 content-type是对应
    @PostMapping("/member/save")
    public Result save(@RequestBody Member member) {
        log.info("service-provider member={}", member);
        int affected = memberService.save(member);
        if (affected > 0) { //说明添加成功
            return Result.success("添加会员成功", affected);
        } else {
            return Result.error("401", "添加会员失败");
        }
    }

    //查询的方法/接口
    //老师这里使用url占位符+@PathVariable
    @GetMapping("/member/get/{id}")
    public Result getMemberById(@PathVariable("id") Long id, HttpServletRequest request) {

        //String color = request.getParameter("color");
        //String address = request.getParameter("address");
        //模拟超时, 休眠5s
//        try {
//            TimeUnit.MILLISECONDS.sleep(5000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }

        Member member = memberService.queryMemberById(id);

        //使用Result把查询到的结果返回
        if (member != null) {
            //return Result.success("查询会员成功 member-service-provider-10000 " + color + "-" + address, member);
            return Result.success("查询会员成功 member-service-provider-10001", member);
        } else {
            return Result.error("402", "ID= " + id + "不存在");
        }

    }
}
